class LogicBuilder extends BuilderSupport {

    def logicBacker

    LogicBuilder(Class c) {
        logicBacker = c.newInstance()
    }

    LogicBuilder(logicBacker) {
        this.logicBacker = logicBacker
    }


    protected void setParent(Object parent, Object child) {
        parent.children << child
    }

    protected Object createNode(Object name) {
        return new ExecutionNode(methodName: name)
    }

    protected Object createNode(Object name, Object value) {
        return new ExecutionNode(methodName: name, args: value)
    }

    protected Object createNode(Object name, Map map) {
        return new ExecutionNode(methodName: name, args: map)
    }

    protected Object createNode(Object name, Map map, Object value) {
        return new ExecutionNode(methodName: name, args: [map, value])
    }

    protected void nodeCompleted(Object parent, Object node) {
        if(!parent) {
            execute(node)
        }
    }

    def execute(node) {
        if(node.executeOn(logicBacker)) {
            node.children.each {
                execute(it)
            }
        }
    }


}

class ExecutionNode {
    String methodName
    def args
    def children = []

    def executeOn(logicBacker) {
        return logicBacker.invokeMethod(methodName, args)
    }
}